import React, { Component } from 'react';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import * as actions from '../actions/index';
import BuildIssuesList from 'components/dependencyBuildIssuesList';
import BranchAndTagSelect from 'components/branchAndTagSelect';
import { navigate, navigateOpen } from 'utils/router';
import utils from 'utils';
import Filter from './filter';
import WarningPage from './warningPage.jsx';
import ListLoading from 'atComponents/ListLoading';
import { YunxiaoIcon } from '@alife/devops-ui';
import { Button, Message } from '@teamix/ui';
import DisabledPage from 'components/projectSecurityDisabledDetail';
import { ENUM, ORGANIZATION_ADMIN_ROLES, PROJECT_ADMIN_ROLES } from 'utils/constants.js';
import { access } from 'components/accessContainer/util';
import { updateData as updateRootData } from 'pages/index/pages/project/pages/projectSecurity/actions/index.js';
import { enterPage, Perf } from 'utils/track';
import { getCachedRepoValue } from 'utils/repoIdCache';
import docs from 'utils/docs';
import intl from '../../../../../../../../../locale';

const prefix = 'project-security-issues-section';
const cacheKey = getCachedRepoValue('user');
// 触发文案
const { triggerText } = ENUM;
class Root extends Component {
  constructor(props) {
    super(props);
    const hasCache = utils.getCachedData(`dependency-analysis-auto-fixed-${cacheKey}`);
    this.state = {
      showAiFixMessage: !hasCache,
    };
  }

  componentDidMount() {
    this.props.resetData();
    this.props.getBuildResult();
    enterPage('repo-security-dependency', {
      sendPerf: false,
    });
  }

  isAdmin = () => {
    const { projectInfo: project } = this.props;
    const { user_role } = window.FORCE.organization;
    return (
      access(ORGANIZATION_ADMIN_ROLES, user_role) ||
      access(PROJECT_ADMIN_ROLES, ENUM.access_level[project.access_level])
    );
  };

  onChange = (value) => {
    const { pathResource } = window.FORCE;
    // 数据清空，刷新数据，出现loading
    navigate(
      `/${pathResource.fullPath}/project_security/dependency_analysis/${encodeURIComponent(value)}`,
    );
    this.props.resetData();
    this.props.updateRootData({
      branchName: value,
    });

    this.props.getBuildResult();
  };

  componentWillUnmount() {
    this.props.resetData();
  }

  isShowWarningPage = () => {
    const { branchName, buildResult, issueCount, incompleteData } = this.props;
    // 可选值RUNNING、PASS、ERROR、WARNING、WAITING、FAIL
    // const state = buildResult ? buildResult.state.toLowerCase() : '';
    return (
      !branchName ||
      !buildResult ||
      !issueCount ||
      (incompleteData &&
        incompleteData.state.toLowerCase() === 'running' &&
        incompleteData.id > buildResult.id) ||
      (incompleteData &&
        incompleteData.state.toLowerCase() === 'error' &&
        incompleteData.id > buildResult.id)
    );
  };

  updateCommitId = (e, commitId) => {
    e.preventDefault();
    e.stopPropagation();
    const { pathResource } = window.FORCE;
    navigateOpen(
      `/${pathResource.fullPath}/commit/${commitId}?branch=${this.props.branchName}`,
      '_blank',
    );
    this.props.updateData({
      curCommitId: commitId,
    });
  };

  closeCommitDetail = () => {
    this.props.updateData({
      curCommitId: '',
    });
  };

  closeAiFixedMsg = () => {
    utils.setCachedData(`dependency-analysis-auto-fixed-${cacheKey}`, true);
    this.setState({
      showAiFixMessage: false,
    });
  };

  renderContent() {
    const {
      branchName,
      buildResult,
      tableParams,
      isLoadingBuild,
      startScan,
      isStarting,
      incompleteData,
      restartScan,
    } = this.props;
    if (isLoadingBuild) {
      return <ListLoading />;
    } else if (this.isShowWarningPage()) {
      return (
        <div className="sensitive-info-warn-page">
          <Perf page="repo-security-dependency" />
          <WarningPage
            buildResult={buildResult}
            startScan={startScan}
            incompleteData={incompleteData}
            restartScan={restartScan}
            isStarting={isStarting}
          />
        </div>
      );
    } else {
      return (
        <>
          <Perf page="repo-security-dependency" />
          <BuildIssuesList
            branchName={branchName}
            buildResult={buildResult}
            filterParams={tableParams}
            updateCommitId={this.updateCommitId}
            restartScan={restartScan}
            isStarting={isStarting}
          />
        </>
      );
    }
  }

  render() {
    const {
      buildResult,
      tableParams,
      start_time,
      end_time,
      branchName,
      issueCount,
      serviceData,
      plugin,
    } = this.props;
    const { showAiFixMessage } = this.state;
    // const { pathResource } = window.FORCE;
    const state = buildResult ? buildResult.state.toLowerCase() : '';
    const isOldData = !issueCount && (state === 'fail' || state === 'warning');
    if (!plugin) {
      return null;
    }
    if (!(serviceData.dependency_analysis && serviceData.dependency_analysis.enabled)) {
      return <DisabledPage isAdmin={this.isAdmin()} plugin={plugin} serviceData={serviceData} />;
    }
    return (
      <div className={`${prefix}`}>
        {showAiFixMessage ? (
          <div className={`${prefix}-message`}>
            <Message onClose={this.closeAiFixedMsg} closeable type="notice">
              <span className="title">
                {intl.get({
                  id: 'code-assets.dependencyAnalysis.containers.root.AutomaticRepair',
                  defaultMessage: '新增自动修复功能',
                })}
              </span>
              <span className="detail">
                {intl.get({
                  id: 'code-assets.dependencyAnalysis.containers.root.AllowsYouToAutomaticallyCreate',
                  defaultMessage:
                    '支持一键自动创建代码，通过合并请求人工审核后完成合并，安全高效地修复风险漏洞。',
                })}
              </span>
              <a href={docs('automaticRepair')} target="_blank" rel="noreferrer">
                {intl.get({
                  id: 'code-assets.dependencyAnalysis.containers.root.LearnMore',
                  defaultMessage: '了解更多',
                })}
              </a>
            </Message>
          </div>
        ) : null}
        <div className={`${prefix}-header`}>
          <div className={`${prefix}-header-left`}>
            <BranchAndTagSelect onChange={this.onChange} value={branchName} needTagSearch={false} />
          </div>
          {buildResult && !isOldData && (
            <div className={`${prefix}-trigger-info ${prefix}-header-right`}>
              <div>
                <YunxiaoIcon
                  type="commit-line"
                  className={`${prefix}-header-right-commit-icon`}
                  style={{ marginLeft: 8 }}
                />
                <span>
                  {intl.get({
                    id: 'code-assets.dependencyAnalysis.containers.root.TheCurrentScanResultIs',
                    defaultMessage: '当前扫描结果基于提交',
                  })}
                  <Button
                    type="primary"
                    text
                    onClick={(e) => {
                      this.updateCommitId(e, buildResult.sha);
                    }}
                  >
                    {buildResult.sha && buildResult.sha.slice(0, 8)}
                  </Button>
                  <span className={`${prefix}-trigger-info-user`}>
                    （{buildResult.trigger_user ? buildResult.trigger_user.name : null}
                    {intl.get({
                      id: 'code-assets.dependencyAnalysis.containers.root.In',
                      defaultMessage: '于',
                    })}
                    {utils.getBeautyTime(buildResult.gmt_create)}{' '}
                    {triggerText[buildResult.mode] || triggerText.default}）
                  </span>
                </span>
              </div>
              <div>
                <Filter
                  tableParams={tableParams}
                  start_time={start_time}
                  end_time={end_time}
                  updateTableParams={this.props.updateTableParams}
                  updateData={this.props.updateData}
                />
              </div>
            </div>
          )}
        </div>
        {this.renderContent()}
      </div>
    );
  }
}

export default connect(
  (state) => ({
    ...state.project.projectSecurity.dependencyAnalysis,
    projectInfo: state.project.root.projectInfo,
    branchName: state.project.projectSecurity.root.branchName,
  }),
  (dispatch) => bindActionCreators({ ...actions, updateRootData }, dispatch),
)(Root);
